package com.fenghuajueli.lib_pictureselect.adapter;

import android.content.ContentResolver;
import android.content.Context;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.util.Size;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.recyclerview.widget.RecyclerView;

import com.blankj.utilcode.util.LogUtils;
import com.fenghuajueli.lib_pictureselect.constants.MediaType;
import com.fenghuajueli.lib_pictureselect.entity.SelectMediaEntity;
import com.fenghuajueli.lib_pictureselect.R;
import com.fenghuajueli.lib_pictureselect.interfaces.OnListItemListener;
import com.fenghuajueli.lib_pictureselect.utils.GlideLoadUtils;
import com.fenghuajueli.lib_pictureselect.utils.MediaSelectDataUtils;
import com.fenghuajueli.lib_pictureselect.utils.VideoCoverCacheUtils;

import java.io.IOException;
import java.util.List;

public class PictureBottomPreviewItemAdapter extends RecyclerView.Adapter<PictureBottomPreviewItemAdapter.ViewHolder> {

    private Context mContext;
    private List<SelectMediaEntity> selectMediaEntityList;
    private OnListItemListener<SelectMediaEntity> onItemClickListener;
    private ContentResolver contentResolver;

    public PictureBottomPreviewItemAdapter(Context mContext, List<SelectMediaEntity> selectMediaEntityList) {
        this.mContext = mContext;
        this.selectMediaEntityList = selectMediaEntityList;
        contentResolver = mContext.getContentResolver();
    }

    public void setOnItemClickListener(OnListItemListener<SelectMediaEntity> onItemClickListener) {
        this.onItemClickListener = onItemClickListener;
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(mContext).inflate(R.layout.picture_bottom_preview_item_layout, parent, false);
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        SelectMediaEntity selectMediaEntity = selectMediaEntityList.get(position);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
            try {
                if (selectMediaEntity.getType() == MediaType.Type.VIDEO) {
                    Bitmap bitmap = VideoCoverCacheUtils.getInstance().getBitmap(selectMediaEntity.getUri());
                    if (bitmap != null) {
                        holder.ivPreviewImg.setImageBitmap(bitmap);
                    } else {
                        new MyImageAsyncTask(selectMediaEntity, position).execute(Uri.parse(selectMediaEntity.getUri()));
                    }
                } else {
                    GlideLoadUtils.load(mContext, Uri.parse(selectMediaEntity.getUri()), holder.ivPreviewImg);
                }
            } catch (Exception e) {
                GlideLoadUtils.load(mContext, Uri.parse(selectMediaEntity.getUri()), holder.ivPreviewImg);
            }
        } else {
            GlideLoadUtils.load(mContext, selectMediaEntity.getPath(), holder.ivPreviewImg);
        }
        if (selectMediaEntity.getType() == MediaType.Type.VIDEO) {
            holder.tvDuration.setVisibility(View.VISIBLE);
            holder.tvDuration.setText(msecToTime(selectMediaEntity.getDuration()));
        } else {
            holder.tvDuration.setVisibility(View.GONE);
            holder.tvDuration.setText("");
        }
        holder.ivDelete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                selectMediaEntity.setChecked(false);
                MediaSelectDataUtils.alreadySelectMediaEntityList.remove(selectMediaEntity);
                notifyDataSetChanged();
                if (onItemClickListener != null) {
                    onItemClickListener.onItemClick(position, selectMediaEntity);
                }
            }
        });
    }

    public void refreshData(List<SelectMediaEntity> selectMediaEntityList) {
        this.selectMediaEntityList = selectMediaEntityList;
        notifyDataSetChanged();
    }

    @Override
    public int getItemCount() {
        return selectMediaEntityList.size();
    }


    public static class ViewHolder extends RecyclerView.ViewHolder {

        public ImageView ivPreviewImg;
        public TextView tvDuration;
        public ImageView ivDelete;


        public ViewHolder(@NonNull View itemView) {
            super(itemView);
            ivPreviewImg = itemView.findViewById(R.id.ivPreviewImg);
            tvDuration = itemView.findViewById(R.id.tvDuration);
            ivDelete = itemView.findViewById(R.id.ivDelete);
        }

    }

    /**
     * 将int类型数字转换成时分秒毫秒的格式数据
     *
     * @param time long类型的数据
     * @return HH:mm:ss.SSS
     */
    public String msecToTime(long time) {
        String timeStr = null;
        long hour = 0;
        long minute = 0;
        long second = 0;
        long millisecond = 0;
        if (time <= 0)
            return "00:00";
        else {
            second = time / 1000;
            minute = second / 60;
            millisecond = time % 1000;
            if (second < 60) {
                timeStr = "00:" + unitFormat(second);
            } else if (minute < 60) {
                second = second % 60;
                timeStr = unitFormat(minute) + ":" + unitFormat(second);
            } else {// 数字>=3600 000的时候
                hour = minute / 60;
                minute = minute % 60;
                second = second - hour * 3600 - minute * 60;
                timeStr = unitFormat(hour) + ":" + unitFormat(minute) + ":" + unitFormat(second);
            }
        }
        return timeStr;
    }


    public static String unitFormat(long i) {// 时分秒的格式转换
        String retStr = null;
        if (i >= 0 && i < 10)
            retStr = "0" + i;
        else
            retStr = "" + i;
        return retStr;
    }

    public static String unitFormat2(long i) {// 毫秒的格式转换
        String retStr = null;
        if (i >= 0 && i < 10)
            retStr = "00" + i;
        else if (i >= 10 && i < 100) {
            retStr = "0" + i;
        } else
            retStr = "" + i;
        return retStr;
    }

    public class MyImageAsyncTask extends AsyncTask<Uri, Void, Bitmap> {
        private SelectMediaEntity selectMediaEntity;
        private int position;

        public MyImageAsyncTask(SelectMediaEntity selectMediaEntity, int position) {
            this.selectMediaEntity = selectMediaEntity;
            this.position = position;
        }

        @RequiresApi(api = Build.VERSION_CODES.Q)
        @Override
        protected Bitmap doInBackground(Uri... params) {
            Bitmap bitmap = null;
            try {
                bitmap = contentResolver.loadThumbnail(params[0], new Size(200, 200), null);
                VideoCoverCacheUtils.getInstance().setBitmap(params[0].toString(), bitmap);
            } catch (IOException e) {
                e.printStackTrace();
                LogUtils.e(e.toString());
            }
            return bitmap;
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();

        }

        @Override
        protected void onPostExecute(Bitmap bitmap) {
            super.onPostExecute(bitmap);
            notifyItemChanged(position);
        }

        @Override
        protected void onProgressUpdate(Void... values) {
            super.onProgressUpdate(values);
        }
    }

}
